package main

import (
	"gitee.com/cristiane/go-common/json"
	"log"
)

// 链表三位数加法

type ListNode struct {
	Val  int
	Next *ListNode
}

//输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
//输出：7 -> 0 -> 8
//原因：342 + 465 = 807

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	var ret = new(ListNode)
	current := ret
	carray := 0
	for l1 != nil || l2 != nil {
		x, y := 0, 0
		if l1 != nil {
			x = l1.Val
			l1 = l1.Next
		}
		if l2 != nil {
			y = l2.Val
			l2 = l2.Next
		}
		sum := x + y + carray
		carray = sum / 10
		current.Next = &ListNode{
			Val:  sum % 10,
			Next: nil,
		}
		current = current.Next
	}
	if carray != 0 {
		current.Next = &ListNode{
			Val:  carray,
			Next: nil,
		}
	}
	return ret.Next
}

func main() {
	l1 := ListNode{
		Val: 2,
		Next: &ListNode{
			Val: 4,
			Next: &ListNode{
				Val:  3,
				Next: nil,
			},
		},
	}

	l2 := ListNode{
		Val: 5,
		Next: &ListNode{
			Val: 6,
			Next: &ListNode{
				Val:  4,
				Next: nil,
			},
		},
	}
	log.Printf("%s", json.MarshalToStringNoError(addTwoNumbers(&l1, &l2)))

}
